import math
import os.path
import random as rand

import docx
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_BREAK
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

oper = ['+', '-', "*", "/"]
colName = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
doc = docx.Document()

'''二元一次方程'''


def saveToDocx(dataList: list, colNum: int = 3, timeDelta: int = 0):
    dataLen = len(dataList)
    rowNum = math.ceil(dataLen / colNum)

    ph = doc.add_paragraph('  ')
    if timeDelta > 0:
        run = ph.runs[0]
        run.add_break(WD_BREAK.PAGE)
    idx = 0
    font = ph.runs[0].font
    font.size = docx.shared.Pt(16)
    table = doc.add_table(rows=rowNum, cols=colNum)
    for i in range(0, rowNum):
        for j in range(0, colNum):
            cellTmp = table.cell(i, j)
            cellTmp.text = "\n" + dataList[idx][0] + " \n " + dataList[idx][1] + "\n"
            cellTmp.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            cellTmp.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            cellTmp.vertical_alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            cellTmp.paragraphs[0].runs[0].font.bold = True
            font = cellTmp.paragraphs[0].runs[0].font
            font.size = docx.shared.Pt(20)
            idx += 1
            if idx == dataLen:
                break


'''生成算式'''


def gen_func(equation):
    arr = []
    for i, n in enumerate(equation):
        arr.append(str(n[0]) + "X" + " " + n[1] + " " + str(n[2]) + "Y" + " = " + str(n[3]))
    return arr


''' 二元一次方程组 '''
if __name__ == '__main__':
    max_rate = 5
    for p in range(0, 14):
        express = []
        for i in range(1, 11):
            rate_x = [rand.randint(1, max_rate), rand.randint(1, max_rate)]
            x = rand.randint(1, max_rate)
            rate_y = [rand.randint(1, max_rate), rand.randint(1, max_rate)]
            y = rand.randint(1, max_rate)
            op1 = oper[rand.randint(0, 1)]
            op2 = oper[rand.randint(0, 1)]
            if op1 == '+':
                result_1 = rate_x[0] * x + rate_y[0] * y
            else:
                result_1 = rate_x[0] * x - rate_y[0] * y
            if op2 == '+':
                result_2 = rate_x[1] * x + rate_y[1] * y
            else:
                result_2 = rate_x[1] * x - rate_y[1] * y

            equation = [[rate_x[0], op1, rate_y[0], result_1], [rate_x[1], op2, rate_y[1], result_2]]
            express.append(gen_func(equation))
        saveToDocx(express, 2, p)
    print(os.path.dirname(os.getcwd()))
    doc.save('test.docx')
